<?php
namespace wlcat\http\controllers;
use wlcat\http\view\View;
use wlcat\src\Register;

class Controller
{
    protected $_controller;
    protected $_action;
    protected $_view;
    protected $request;
    protected $token;
    // 构造函数，初始化属性，并实例化对应模型
    function __construct($controller, $action)
    {
        $this->_controller  = $controller;
        $this->_action      = $action;
        $this->_view        = new View($controller, $action);
        $this->request      = Register::get(Register::REQUEST_CLASS);
    }
    // 分配变量
    function assign($name, $value)
    {
        $this->_view->assign($name, $value);
    }
    function display($file = '')
    {
        $this->_view->display($file);
    }
    function success($info, $url, $time = 3)
    {
        $this->assign('info', $info);
        $this->assign('time', $time);
        $this->assign('url', $url);
        $this->display('success.php');
        exit;
    }

    function error($info, $time = 3)
    {
        $this->assign('info', $info);
        $this->assign('time', $time);
        $this->display('error.php');
        exit;
    }

    function assignFormToken()
    {
        $this->assign('__token__', "<input type='hidden' name='__token__' value='{$this->setToken()}'>");
    }

    function setToken()
    {
        $this->token = getRandomString(60);
        $this->request->setInput('session.__token__', $this->token);
        return $this->token;
    }
    function checkFormToken($showPage = true)
    {
        $token = $this->request->input('post.__token__', null);
        if (empty($token))
        {
            $token = $this->request->input('get.__token__', null);
        }

        if (empty($token)
            || $token != $this->request->input('session.__token__')
        ) {
            if ($showPage)
            {
                $this->error('表单token错误');
                exit;
            } else {
                return false;
            }
        }
        return true;
    }
}